package bud.taskmanager.project;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import bud.taskmanager.project.dto.Project;
import bud.taskmanager.project.service.ProjectService;


@Controller
public class ProjectController {

	@Autowired
	private ProjectService projectService;

	@RequestMapping(value = "/projects", method = RequestMethod.GET)
	public String list(ModelMap model) {
		model.addAttribute("projects", projectService.findAllProjects());
		return "project/list";
	}

	@RequestMapping(value = "/projects/new", method = RequestMethod.GET)
	public String form(ModelMap model) {
		model.addAttribute("project", new Project());
		return "project/form";
	}

	@RequestMapping(value = "/projects/new", method = RequestMethod.POST)
	public String formSubmit(@ModelAttribute("project") @Valid Project project, BindingResult result) {
		if (result.hasErrors()) {
			return "project/form";
		}
		
		if (project.getId() > 0) {
			projectService.updateProject(project);
		} else {
			projectService.createProject(project);
		}

		return "redirect:";
	}

	@RequestMapping(value = "/projects/delete/{id}")
	public String delete(@PathVariable("id") int id) {
		projectService.deleteProject(id);
		return "redirect:..";
	}

	@RequestMapping(value = "/projects/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable("id") int id, ModelMap model) {
		model.addAttribute("project", projectService.findProject(id));
		return "project/form";
	}
}
